<template>
  <t-card :bordered="false">
    <!-- 搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleInitTable">
      <t-col :span="3">
        <t-form-item label="表单名称" prop="name">
          <t-input v-model="params.name" placeholder="请输入表单名称" clearable />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 表格 -->
    <custom-table ref="customTableRef" row-key="id" :columns="columns" :api="formCRUD.page"
      column-controller-key="BpmFormList">
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button v-permission="['bpm:form:create']" @click="openForm">新增表单</t-button>
        </div>
      </template>
      <template #status="{ row }">
        <t-tag variant="light" :theme="row.status === 0 ? 'success' : 'danger'">
          {{ row.status === 0 ? '开启' : '关闭' }}
        </t-tag>
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-link
              v-permission="['bpm:form:query']"
              theme="primary"
              @click="handleFormDetail(row)"
            >
              详情
            </t-link>
          <t-link v-permission="['bpm:form:update']" theme="primary" @click="openForm(row.id)">
            编辑
          </t-link>
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link v-permission="['bpm:form:delete']" theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 弹窗：表单详情 -->
    <t-dialog header="表单详情" v-model:visible="formDetailVisible" width="800">
      <div v-if="formDetailPreview.rule ">
        <form-create
          v-model="formDetailPreview.formData"
          :rule="formDetailPreview.rule"
          :option="formDetailPreview.option"
        />
      </div>
      <div v-else>暂无表单数据</div>
    </t-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'BpmForm',
};
</script>

<script lang="ts" setup>
import dayjs from 'dayjs';
import { onMounted, ref, useTemplateRef } from 'vue';
import { DialogPlugin, MessagePlugin, TableCol } from 'tdesign-vue-next';
import { useRouter } from 'vue-router';

import { formCRUD } from '@/api/bpm/form';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import FormCreate from '@/components/FormCreate/index.vue';
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// // 自定义对话框ref
// const customDialogRef = useTemplateRef('customDialogRef');
interface FormField {
  field: string;
  title: string;
  type: string;
  value?: any;
  props?: {
    placeholder?: string;
    options?: Array<{ label: string; value: any }>;
  };
  validate?: any[];
}

// 表单详情
const formDetailVisible = ref(false);
const formDetailPreview = ref<{
  rule: FormField[];
  formData: Record<string, any>;
  option: Record<string, any>;
}>({
  rule: [],
  formData: {},
  option: {
    submitBtn: false,
    form: {
      disabled: true
    }
  },
});
// columns
const columns: TableCol[] = [
  { colKey: 'id', title: '编号', width: 80 },
  { colKey: 'name', title: '表单名称' },
  { colKey: 'status', title: '开启状态', width: 100 },
  { colKey: 'remark', title: '备注' },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 200 },
];

// 处理初始化表格
const handleInitTable = () => {
  customTableRef.value.initTable(customSearchRef.value.params);
};

// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};

// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params?: Record<string, any>) => {
//   customDialogRef.value.open(mode, params);
};
// 处理表单详情
const handleFormDetail = async (row: Record<string, any>) => {
    try {
      // 设置表单
      const data = await formCRUD.get({ id: row.id });
      
      // 解析字段配置
      let fields: FormField[] = [];
      let conf = {};
      
      try {
        // 解析配置
        conf = JSON.parse(data.conf || '{}');
        
        // 解析字段 - 注意：fields 是字符串数组，每个元素都是 JSON 字符串
        fields = data.fields.map((fieldStr: string) => {
          try {
            const field = JSON.parse(fieldStr);
            return {
              field: field.field || '',
              title: field.title || '',
              type: field.type || 'input',
              value: field.value,
              props: {
                placeholder: `请输入${field.title || ''}`,
                ...field.props,
                // 添加必填验证
                required: field.$required
              },
              validate: field.$required ? [{ required: true, message: `${field.title}必填` }] : undefined
            };
          } catch (fieldError) {
            console.error('解析字段配置失败:', fieldError);
            return null;
          }
        }).filter(Boolean) as FormField[];
      } catch (parseError) {
        console.error('解析表单配置失败:', parseError);
        fields = [];
        conf = {};
      }

      // 更新表单预览数据
      formDetailPreview.value = {
        rule: fields,
        formData: {},
        option: {
          ...conf,
          form: {
            ...(conf as any).form,
            disabled: true
          }
        }
      };

      // 弹窗打开
      formDetailVisible.value = true;
    } catch (error) {
      console.error('获取表单数据失败:', error);
      MessagePlugin.error('获取表单数据失败');
    }
  
};
/** 添加/修改操作 */
const openForm = (id?: number) => {
  const toRouter: { name: string; query?: { id: number } } = {
    name: 'ApproveFormEditor'
  }
  // 表单新建的时候id传的是event需要排除
  if (typeof id === 'number') {
    toRouter.query = {
      id
    }
  }
  router.push(toRouter)
}

// 处理删除
const handleDelete = (params: Record<string, any>) => {
  formCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
const router = useRouter();

onMounted(() => {
  handleInitTable();
});
</script> 